package org.jeecg.modules.basedata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.BaseRoom;
import org.jeecg.entity.basedata.BaseTenant;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.enums.base.DepartPropertyEnum;
import org.jeecg.modules.basedata.mapper.BaseProjectMapper;
import org.jeecg.modules.basedata.mapper.BaseTenantMapper;
import org.jeecg.modules.basedata.service.IBaseProjectService;
import org.jeecg.modules.basedata.service.IBaseRoomService;
import org.jeecg.modules.basedata.service.IBaseTenantService;
import org.jeecg.vo.basedata.BaseTenantPage;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.util.FindsDepartsChildrenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 租户
 * @Author: jeecg-boot
 * @Date:   2019-07-30
 * @Version: V1.0
 */
@Service
public class BaseTenantServiceImpl extends ServiceImpl<BaseTenantMapper, BaseTenant> implements IBaseTenantService {


    @Autowired
    private BaseTenantMapper baseTenantMapper;
    @Autowired
    private BaseProjectMapper baseProjectMapper;
    @Autowired
    private IBaseProjectService baseProjectService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private IBaseRoomService baseRoomService;

    @Override
    public Page<BaseTenantPage> getBaseTenantList(Page<BaseTenantPage> page, BaseTenantPage tenantPage) {
        //log.info("======================"+wrapper.getCustomSqlSegment());
        //log.info("======================"+wrapper.getSqlSegment());
        return page.setRecords(baseTenantMapper.getBaseTenantPage(page, tenantPage));
    }

    @Override
    public List<SysDepartTreeModel> queryTenantTreeList(String menuPath) {
        List<SysDepartTreeModel> list = new ArrayList<>();
        if (StringUtils.isNotBlank(menuPath)) {
            //根据权限加载
            List<SysDepart> departTreeList = sysUserRoleService.queryDepartTreeList(menuPath, SsoUtil.getLoginUser().getId(), CommonConstant.DEPART_WHERE_CO);
            List<String> departIdList = new ArrayList<>();
            Map<String, SysDepart> departTreeMap = new HashMap<>();
            List<SysDepartTreeModel> branchList = new ArrayList<>();
            for (SysDepart departTree : departTreeList) {
                departTreeMap.put(departTree.getId(), departTree);
                departIdList.add(departTree.getId());
                if (departTree.getType().equals(DepartPropertyEnum.DEPART_PROPERTY_OFFICE.getCode())) continue;
                SysDepartTreeModel branch = new SysDepartTreeModel(departTree);
                branchList.add(branch);
            }
            List<DepartIdModel> idList = new ArrayList<>();
            for (SysDepart depart : departTreeList) {
                if (depart.getType().equals(DepartPropertyEnum.DEPART_PROPERTY_DEPARTMENT.getCode())) continue;
                if (depart.getType().equals(DepartPropertyEnum.DEPART_PROPERTY_OFFICE.getCode())) continue;
                if ((StringUtils.isBlank(depart.getParentId())) || (StringUtils.isNotBlank(depart.getParentId()) && !departTreeMap.containsKey(depart.getParentId()))) {
                    SysDepartTreeModel branch = new SysDepartTreeModel(depart);
                    list.add(branch);
                    DepartIdModel departIdModel = new DepartIdModel().convert(branch);
                    idList.add(departIdModel);
                }
            }
            if (departTreeList.size() > 0) {
                if (departTreeList.size() > 0) {
                    List<SysDepart> projectTreeList = sysUserRoleService.queryProjectTreeListByDepartId(departIdList);
                    for (SysDepart project : projectTreeList) {
                        SysDepartTreeModel branch = new SysDepartTreeModel(project);
                        List<SysDepartTreeModel> listAll = baseProjectMapper.queryUnitTreeList(project.getId());
                        if (listAll != null && listAll.size() > 0) {
                            for (SysDepartTreeModel treeModel : listAll) {
                                List<SysDepartTreeModel> roomList = baseTenantMapper.queryTenantTreeList(treeModel.getId());
                                if (roomList != null && roomList.size() > 0) {
                                    for (SysDepartTreeModel room : roomList) {
                                        room.setKey(room.getId());
                                        room.setValue(room.getId());
                                        room.setIsLeaf(true);
                                        room.setTitle(room.getDepartName());
                                    }
                                    branchList.addAll(roomList);
                                }
                            }
                            branchList.addAll(listAll);
                        }
                        branchList.add(branch);
                    }
                    FindsDepartsChildrenUtil.getGrandChildren(list, branchList, idList);
                    FindsDepartsChildrenUtil.setEmptyChildrenAsNull(list);
                }
            }
        }
        return list;
    }

    @Override
    public List<SysDepartTreeModel> querFloorTreList() {
        LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
        query.eq(SysDepart::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
        query.eq(SysDepart::getDepartProperty,CommonConstant.DEPART_PROPERTY_COMPANY);
        query.orderByAsc(SysDepart::getDepartOrder);
        List<SysDepart> list = baseTenantMapper.querFloorTreList();
        // 调用wrapTreeDataToTreeList方法生成树状数据
        List<SysDepartTreeModel> listResult = FindsDepartsChildrenUtil.wrapTreeDataToTreeList(list,"floor");
        return listResult;
    }

    public String  getByTenantId(String roomId){
        String  id = baseTenantMapper.getByTenantId(roomId);
        return id;
    }

    @Override
    public BaseTenant getTenantByRoomId(String roomId) {
        return baseTenantMapper.getTenantByRoomId(roomId);
    }

    public String  getByCustomerId(String roomId){
        String  id = baseTenantMapper.getByCustomerId(roomId);
        return id;
    }

    @Override
    @Transactional
    public void addBatchTenant(List<BaseRoom> roomList, List<BaseTenant> tenantList) {
        try {
            this.saveBatch(tenantList);
            baseRoomService.updateBatchRoomStatus(roomList);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    @Override
    public BaseTenant detailById(String id,String methodId) {
        return baseTenantMapper.detailById(id, methodId);
    }

    @Override
    public List<BaseTenant> getTenant(BaseTenant baseTenant){
        return baseTenantMapper.getTenant(baseTenant);
    }

}
